package com.mobilesales.android.adapters;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.mobilesales.android.R;
import com.mobilesales.android.model.clients.Client;

public class ClientSimpleArrayAdapter extends ArrayAdapter<Client> {
	
	private boolean isNullable;
	
	public ClientSimpleArrayAdapter(Context context, int textViewResourceId,
			List<Client> objects, boolean isNullable) {

		super(context, textViewResourceId, R.id.selectItemTxt, new ArrayList<Client>(objects));
		
		this.isNullable = isNullable;
		if (isNullable) {			
			Client cli = new Client();
			cli.Name = context.getString(R.string.None);
			this.add(cli);
		}
	}

	
	
	public boolean isNullable() {
		return isNullable;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
					"layout_inflater");
			v = vi.inflate(R.layout.select_list_item, null);
		}

		Client client = null;
		if ((position >= 0) && (position < this.getCount())) {
			client = this.getItem(position);
		}

		TextView nameField = (TextView) v.findViewById(R.id.selectItemTxt);
		if (client != null) {
			nameField.setText(client.Name);
		}
		return v;
	}
	
	@Override
	public View getDropDownView(int position, View convertView, ViewGroup parent) {
		return getView(position, convertView, parent);
	}

	public int getPosition(Integer clientId) {
			if (clientId==null) clientId = 0;
			for (int i = this.isNullable() ? 1 : 0; i < this.getCount(); i++) {
				if (this.getItem(i).Id == clientId)
					return i;
			}
			return -1;
	}	
	
	
	
	
}